package com.easy.service.impl;

import com.easy.bean.Book;
import com.easy.bean.Borrow;
import com.easy.mapper.BookDao;
import com.easy.mapper.BorrowDao;
import com.easy.service.BorrowService;
import com.easy.util.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class BorrowServiceImpl implements BorrowService {

    @Autowired
    private BorrowDao borrowDao;

    @Autowired
    private BookDao bookDao;

    @Override
    @Transactional
    public Borrow borrowBook(Integer user_id, Integer book_id) {

        // 检查书籍库存
        Book book = bookDao.one(book_id);
        if (book == null || book.getNum() <= 0) {
            throw new RuntimeException("书籍库存不足");
        }

        // 创建借阅记录
        Borrow borrow = new Borrow();
        borrow.setUser_id(user_id);
        borrow.setBook_id(book_id);
        borrow.setCreate_time(new Date());
        borrow.setIs_return(0); // 0表示未归还

        // 保存借阅记录
        borrowDao.add(borrow);

        // 减少书籍库存
        book.setNum(book.getNum() - 1);
        bookDao.edit(book);

        return borrowDao.one(borrow.getId());
    }

    @Override
    @Transactional
    public Borrow returnBook(Integer borrowId) {
        // 查询借阅记录
        Borrow borrow = borrowDao.one(borrowId);
        if (borrow == null) {
            throw new RuntimeException("借阅记录不存在");
        }

        if (borrow.getIs_return() == 1) {
            throw new RuntimeException("该书籍已归还");
        }

        // 更新归还信息
        borrow.setReturn_time(new Date());
        borrow.setIs_return(1); // 1表示已归还
        borrowDao.update(borrow);

        // 增加书籍库存
        Book book = bookDao.one(borrow.getBook_id());
        if (book != null) {
            book.setNum(book.getNum() + 1);
            bookDao.edit(book);
        }

        return borrowDao.one(borrowId);
    }

    @Override
    public Borrow one(Integer id) {
        return borrowDao.one(id);
    }

    @Override
    public List<Borrow> findByUser(Integer user_id) {
        return borrowDao.findByUser(user_id);
    }

    @Override
    public List<Borrow> findByBook(Integer book_id) {
        return borrowDao.findByBook(book_id);
    }

    @Override
    public List<Borrow> all(Borrow borrow) {
        return borrowDao.all(borrow);
    }

    @Override
    public void page(Page page, Borrow borrow) {
        int count = borrowDao.pageCount(borrow);
        Object data = borrowDao.page(page, borrow);
        page.setCount(count);
        page.setData(data);
    }

    @Override
    public List<Borrow> findNotReturnByUser(Integer user_id) {
        return borrowDao.findNotReturnByUser(user_id);
    }
}